
package com.basestone.pdlmis.util
{
    import com.basestone.pdlmis.view.DefectListView;
    import com.basestone.pdlmis.util.*;


    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.utils.Timer;
    import flash.xml.XMLDocument;
    import flash.xml.XMLNode;

    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.controls.dataGridClasses.DataGridColumn;
    import mx.events.ListEvent;
    import mx.events.ToolTipEvent;
    import mx.formatters.CurrencyFormatter;
    import mx.formatters.NumberFormatter;
    import mx.managers.CursorManager;
    import mx.core.Application;
    import mx.collections.Sort;
    import mx.collections.SortField;
    import mx.utils.ObjectUtil;


    public class List
    {
        //########################################################################################
        /*
         * Local Variables
         */
        // A list view GUI
        public var listView:DefectListView;

        // The list view state
        public var currentState:String;

        // A caller ID
        public var listViewCallerID:int;

        // A page control ID
        public var pageControlID:int;

        // A set of selected items
        public var selectedItems:*;

        // A list view title
        public var selectedView:String;

        // A request URL
        public var selectedURL:String;

        // A database table name
        public var selectedTable:String;

        // A database name
        public var selectedDatabase:String;

        // Internal method variables
        public var methodForGettingIndices:String;
        public var methodForCountingRecords:String;
        public var methodForGettingRecords:String;

        // A flag for displaying an image
        public var openImage:Boolean;

        // A flag for displaing a graphical chart
        public var openGraph:Boolean;

        // A flag for displaying a dollar value
        public var setDollarValue:Boolean;

        // A flag for DataGrid double-click
        public var isDoubleClickAllowed:Boolean;

        // A flag for getting indices
        public var isCountingIndicesRequired:Boolean;

        // A flag for counting the number of records
        public var isCountingRecordsRequired:Boolean;

        // A column name for dollar values
        public var totalColumn:String;

        // A column name for hits
        public var hitColumn:String;

        // A column name for ordering records
        public var orderColumn:String;

        // An abstract data structure for ordering records
        public var orderColumnData:Object;

        // An abstract data structre for sorting records
        public var sortableColumns:Object;

        // File Upload Variable
        private var fileUploadParameters:Object;

        // Date filters for usage history
        public var yearFilter:Number;
        public var monthFilter:Number;
        public var dateFilter:Number;

        // An extra filter
        public var extraFilter:String;

        // Variables for dynamic filter
        public var customers:ArrayCollection;
        public var selectedCustomer:Object;

        // Variable for page control
        public const maxNumOfPages:int=4000000; // TODO: Set this value for your application.
        public var currentPageNum:int;
        public var numOfPages:int;
        public var numOfRecords:int;
        public var total:Number;
        public var hits:Number;
        public var indexOfPageSizeCombobox:int;

        // A maximum width for menu control
        public var minimumWidth:int;

        // An abstruct data structure for target turns
        public var trendParameters:Object;

        // An abstruct data structure for extra parameters
        public var extraParameters:Object;

        // A callback function for updating list
        private var updateCallback:Function;

        // A call-back function for deletion control
        public var callbackFunction:Function;

        // Tooltip provider
        private var toolTipProvider:*;

//        // Export Provider
//        private var exportProvider:WebClient_Export;
//        
//        // Download Provider
//        private var downloadProvider:WebClient_Download;
//        
//        // Image Provider
//        private var imageProvider:WebClient_Image;


        //########################################################################################
        /*
         * Constructor
         */
        /**
         * Default Constructor
         */
        public function List(listView:DefectListView)
        {
            this.listView=listView;
            this.orderColumnData={'index': '0', 'name': '', 'order': 'ASC', 'type': 'string'};
            this.selectedItems=null;
            this.sortableColumns=null;
            this.currentPageNum=0;
            this.numOfPages=0;
            this.numOfRecords=0;
//            this.exportProvider = new WebClient_Export();
//            this.downloadProvider = new WebClient_Download();
//            this.imageProvider = new WebClient_Image();
        }


        //########################################################################################
        /*
         * Public Functions
         */
        /**
         * Sets a set of parameters to populate records.
         * @param parameters            A set of parameters
         */
        public function setParameters(parameters:Object):void
        {
            if (parameters != null)
            {
                this.currentState=parameters[Constant.CURRENT_STATE.toString()];
                this.listViewCallerID=parameters[Constant.CALLER_ID.toString()];
                this.pageControlID=parameters[Constant.PAGE_CONTROL_ID.toString()];
                this.selectedView=parameters[Constant.SELECTED_VIEW.toString()];
                this.selectedURL=parameters[Constant.SELECTED_URL.toString()];
                this.selectedTable=parameters[Constant.SELECTED_TABLE.toString()];
                this.selectedDatabase=parameters[Constant.SELECTED_DATABASE.toString()];
                this.methodForGettingIndices=parameters[Constant.INDEX_METHOD.toString()];
                this.methodForCountingRecords=parameters[Constant.COUNT_METHOD.toString()];
                this.methodForGettingRecords=parameters[Constant.POPULATE_METHOD.toString()];
                this.openImage=parameters[Constant.OPEN_IMAGE.toString()];
                this.openGraph=parameters[Constant.OPEN_GRAPH.toString()];
                this.setDollarValue=parameters[Constant.SET_TOTAL.toString()];
                this.isDoubleClickAllowed=parameters[Constant.IS_DOUBLE_CLICK_ALLOWED.toString()];
                this.isCountingIndicesRequired=parameters[Constant.IS_COUNTING_INDICES_ALLOWED.toString()];
                this.isCountingRecordsRequired=parameters[Constant.IS_COUNTING_RECORDS_ALLOWED.toString()];
                this.totalColumn=parameters[Constant.TOTAL_COLUMN.toString()];
                this.hitColumn=parameters[Constant.HIT_COLUMN.toString()];
                this.orderColumn=parameters[Constant.ORDER_COLUMN.toString()];
                this.yearFilter=parameters[Constant.YEAR_FILTER.toString()];
                this.monthFilter=parameters[Constant.MONTH_FILTER.toString()];
                this.dateFilter=parameters[Constant.DATE_FILTER.toString()];
                this.extraFilter=parameters[Constant.EXTRA_FILTER.toString()];
                this.customers=parameters[Constant.CUSTOMER_DATA.toString()];
                this.selectedCustomer=parameters[Constant.SLECTED_CUSTOMER.toString()];
                this.indexOfPageSizeCombobox=parameters[Constant.PAGE_SIZE_INDEX.toString()];
                this.minimumWidth=parameters[Constant.MINIMUM_WIDTH.toString()];
                this.trendParameters=parameters[Constant.TREND_PARAMETERS.toString()];
                this.extraParameters=parameters[Constant.EXTRA_PARAMETERS.toString()];
                this.fileUploadParameters=parameters[Constant.FILE_UPLOAD_PARAM.toString()];
                this.callbackFunction=parameters[Constant.CALLBACK_FUNCTION.toString()];
            }
        }

        public function deleteItems(event:*):void
        {
//            if ( event.detail == Alert.YES ) {
//                CursorManager.setBusyCursor();
//                listView.ListView_TableData.removeAll();
//                
//                var parameters:Object = new Object();
//                parameters['callerID'] = listViewCallerID;
//                parameters['systemMethod'] = Constant.METHOD_EXEC_SQL;
//                parameters['database'] = selectedDatabase;
//                parameters['table'] = selectedTable;
//                parameters['flagColumn'] = WebClient_Workspace.DELETE_FLAGS[listViewCallerID];
//                parameters['columns'] = listView.ListView_DataGrid.columns;
//                parameters['selectedItems'] = selectedItems;
//                
//                WebClient_HTTPService.sendRequest(
//                    Constant.METHOD_DELETE_ITEMS, 
//                    parameters, 
//                    deleteItemsEventHandler);
//            }
//            else {
//                CursorManager.removeAllCursors();
////                WebClient_HTTPService.activeAllSelectedUIObjects();
//            }
        }

        /**
         * Exports records in the current list view to an Excel file.
         */
        public function exportList():void
        {
            var today:Date=new Date();
            var parameters:Object={'appName': Constant.APP_ID, 'systemMethod': Constant.METHOD_GET_EXCEL, 'internalMethod': methodForGettingRecords, 'callerID': listViewCallerID, 'database': selectedDatabase, 'table': selectedTable, 'extraFilter': extraFilter, 'orderColumn': orderColumnData, 'orderColumnName': "", 'isRecordRangeRequired': false, 'searchFlag': listView.isSearchFunctionClicked, 'filename': selectedView.replace(/[\/]/gi, "-") + "(Y" + today.getFullYear() + "_M" + (today.getMonth() + 1) + "_D" + today.getDate() + "_h" + today.getHours() + "_m" + today.getMinutes() + ")", 'preYear': yearFilter - 1, 'thisYear': yearFilter, 'thisMonth': monthFilter, 'date': dateFilter, 'customers': customers, 'selectedCustomer': selectedCustomer, 'trendParameters': trendParameters, 'extraParameters': extraParameters};
//            exportProvider.export(parameters);
        }

//        /**
//         * Uploads a file on Web server.
//         * @param selectedItem          A record
//         */
//        public function uploadFile(selectedItem:*):void 
//        {
//            uploadProvider.uploadFile(listViewCallerID, selectedItem, listView.updateListView);
//        }

        /**
         * Uploads files on the Web server.
         * @param selectedItem          A record
         * @param callbackFunction      A callback function
         */
        public function uploadFile(selectedItem:*, callbackFunction:Function):void
        {
            if (fileUploadParameters != null)
            {
                Application.application.FileProvider.openWndow(listViewCallerID, callbackFunction);
            }
        }


        /**
         * Downloads a file from Web server.
         * @param selectedItem          A record
         */
        public function downloadFile(selectedItem:*):void
        {
//            downloadProvider.downloadFile(listViewCallerID, selectedItem);
        }

        /**
         * Displays an image.
         * @param selectedItem          A record
         */
        public function displayImage(selectedItem:*):void
        {
//            imageProvider.openImageView(listViewCallerID, selectedItem);
        }

        /**
         * Converts a string to a currency.
         * @param number
         * @param precision
         * @param currencySymbol
         * @return                      A currency in string
         */
        public function getCurrencyFormat(number:String, precision:Number, currencySymbol:String="$"):String
        {
            var currencyFormatter:CurrencyFormatter=new CurrencyFormatter();
            currencyFormatter.decimalSeparatorTo=".";
            currencyFormatter.rounding="up";
            currencyFormatter.precision=precision;
            currencyFormatter.currencySymbol=currencySymbol;
            currencyFormatter.useNegativeSign=true;
            currencyFormatter.thousandsSeparatorTo=",";
            currencyFormatter.useThousandsSeparator=true;
            return currencyFormatter.format(number);
        }

        /**
         * Converts a string to a number.
         * @param number
         * @param precision
         * @return                      A number in string
         */
        public function getNumberFormat(number:String, precision:Number=0):String
        {
            var numberFormatter:NumberFormatter=new NumberFormatter();
            numberFormatter.precision=precision;
            numberFormatter.rounding="up";
            numberFormatter.useNegativeSign=true;
            numberFormatter.thousandsSeparatorTo=",";
            numberFormatter.useThousandsSeparator=true;
            return numberFormatter.format(number);
        }


        //########################################################################################
        /*
         * Event Handlers
         */
        /**
         * An event handler to get the indices of a talbe from a server response
         * and send the next function call for getting the number of records.
         * @param event                 A server response
         */
        private function getIndicesEventHandler(event:*):void
        {
            if (getSortableColumns(event))
            {
                var parameters:Object=new Object();
                parameters['appName']=Constant.APP_ID;
                parameters['systemMethod']=selectedURL;
                parameters['database']=selectedDatabase;
                parameters['table']=selectedTable;
                parameters['extraFilter']=extraFilter;
                parameters['searchFlag']=listView.isSearchFunctionClicked;
                if (listView.isSearchFunctionClicked)
                {
//                    parameters['searchFilters'] = listView.advancedSearchFilter.advancedSearchView.filterList;
                    parameters['columns']=listView.ListView_DataGrid.columns;
                }
                if (pageControlID == Constant.PAGE_CONTROL_ID_DEFAULT)
                {
                    if (isCountingRecordsRequired)
                    {
                        parameters['isCountingRecordsRequired']=true;
                    }
                    else
                    {
                        parameters['isCountingRecordsRequired']=false;
                    }
                }
                else if (pageControlID == Constant.PAGE_CONTROL_ID_SERACH)
                {
                    parameters['isCountingRecordsRequired']=true;
                }
                else
                {
                    if (setDollarValue)
                    {
                        parameters['isCountingRecordsRequired']=true;
                    }
                    else
                    {
                        parameters['isCountingRecordsRequired']=false;
                    }
                }
                parameters['preYear']=yearFilter - 1;
                parameters['thisYear']=yearFilter;
                parameters['thisMonth']=monthFilter;
                parameters['date']=dateFilter;
                parameters['customers']=customers;
                parameters['selectedCustomer']=selectedCustomer;
                parameters['trendParameters']=trendParameters;
                parameters['extraParameters']=extraParameters;

//                WebClient_HTTPService.sendRequest(
//                    methodForCountingRecords, parameters, getNumOfRecordsEventHandler);
            }
            else
            {
                Alert.show("It is unable to get the indices of " + selectedView.toLowerCase() + " list. Please try again.", "SERVER ERROR", Alert.OK, null, null, Constant.errorImage, Alert.OK);
                CursorManager.removeAllCursors();
//                WebClient_HTTPService.activeAllSelectedUIObjects();
            }
        }

        /**
         * An event handler to get the number of record from a server response
         * and send the next function call for populating records.
         * @param event                 A server response
         */
        private function getNumOfRecordsEventHandler(event:*):void
        {
            if (getPageNumbers(event))
            {
                var parameters:Object=new Object();
                parameters['appName']=Constant.APP_ID;
                parameters['systemMethod']=selectedURL;
                parameters['callerID']=listViewCallerID;
                parameters['database']=selectedDatabase;
                parameters['table']=selectedTable;
                parameters['extraFilter']=extraFilter;
                parameters['orderColumn']=orderColumnData;
                parameters['orderColumnName']=orderColumn;
                parameters['isRecordRangeRequired']=true;
                parameters['pageNumber']=currentPageNum;
                parameters['pageSize']=new int(listView.ListView_PageSizeCombo.selectedLabel);
                parameters['searchFlag']=listView.isSearchFunctionClicked;
                if (listView.isSearchFunctionClicked)
                {
//                    parameters['searchFilters'] = listView.advancedSearchFilter.advancedSearchView.filterList;
                    parameters['columns']=listView.ListView_DataGrid.columns;
                }
                parameters['preYear']=yearFilter - 1;
                parameters['thisYear']=yearFilter;
                parameters['thisMonth']=monthFilter;
                parameters['date']=dateFilter;
                parameters['customers']=customers;
                parameters['selectedCustomer']=selectedCustomer;
                parameters['trendParameters']=trendParameters;
                parameters['extraParameters']=extraParameters;

//                WebClient_HTTPService.sendRequest(
//                    methodForGettingRecords, parameters, getRecordsEventHandler);
            }
            else
            {
                Alert.show("It is unable to get the number of records in " + selectedView.toLowerCase() + " list. Please try again.", "SERVER ERROR", Alert.OK, null, null, Constant.errorImage, Alert.OK);
                CursorManager.removeAllCursors();
//                WebClient_HTTPService.activeAllSelectedUIObjects();
            }
        }

        /**
         * An event handler to parse and get records from a server response.
         * @param event                 A server response
         */
        private function getRecordsEventHandler(event:*):void
        {
            var isRecordEmpty:Boolean;
            var columnSet:ArrayCollection;
            var newRecord:Object;

            if (!event.isError)
            {
                columnSet=getColumns(event.data);

                for each (var record:XML in event.data.child("Record"))
                {
                    isRecordEmpty=true;
                    newRecord=new Object();
                    for each (var key:String in columnSet)
                    {
                        if (record[key].toString().length > 0)
                        {
                            isRecordEmpty=false;
                        }
                        newRecord[key]=record[key];
                    }

                    if (!isRecordEmpty)
                    {
                        newRecord["CALLER_ID"]=listViewCallerID;
                        newRecord["TREND_PARAMETERS"]=trendParameters;
                        listView.ListView_TableData.addItem(newRecord);
                    }
                }

                if (updateCallback != null)
                {
                    updateCallback();
                    updateCallback=null;
                }

                if (listView.isSearchFunctionClicked)
                {
                    if (listView.ListView_TableData.length == 0)
                    {
//                        listView.advancedSearchFilter.openAdvancedSearchView();
                        alert(500, "NO RECORD FOUND", "You selected more than one search criteria. " + "Revising your search criteria(s) may improve the search result.", Constant.infoImage);
                    }
                }
            }
            else
            {
                Alert.show("It is unable to get the records of " + selectedView.toLowerCase() + " list. Please try again.", "SERVER ERROR", Alert.OK, null, null, Constant.errorImage, Alert.OK);
            }

            CursorManager.removeAllCursors();
//            WebClient_HTTPService.activeAllSelectedUIObjects();
        }

        /**
         * An event handler to get the result of a delete request from a server response.
         * @param event                 A server response
         */
        private function deleteItemsEventHandler(event:*):void
        {
            var errorMessage:String;

            if (!event.isError)
            {
                if (event.data.status.toString() == Constant.STATUS_CODE_SUCCESSFUL)
                {
                    Alert.show("The selected record(s) is(are) deleted successfully.", "Item(s) Deleted", Alert.OK, null, null, Constant.infoImage, Alert.OK);
                    if (callbackFunction != null)
                    {
                        callbackFunction();
                    }
                }
                else
                {
                    if (Constant.IS_DEBUG)
                    {
                        errorMessage="Unable to delete the selected record(s).\n" + event.data.toString();
                    }
                    else
                    {
                        errorMessage="Unable to delete the selected record(s).";
                    }
                    Alert.show(errorMessage, "DELETION FAILED [Server Error]", Alert.OK, null, null, Constant.errorImage, Alert.OK);
                }

                listView.updateListView();
            }
            else
            {
                if (Constant.IS_DEBUG)
                {
                    errorMessage="Unable to delete the selected record(s).\n" + event.data.toString();
                }
                else
                {
                    errorMessage="Unable to delete the selected record(s).";
                }
                Alert.show(errorMessage, "DELETION FAILED [Server Error]", Alert.OK, null, null, Constant.errorImage, Alert.OK);
            }

            selectedItems=null;
            CursorManager.removeAllCursors();
//            WebClient_HTTPService.activeAllSelectedUIObjects();
        }

        //########################################################################################
        /*
         * Private Functions
         */
        /**
         * Gets a set of the sortable columns of a table from a server response.
         * @param event                 A server response
         * @return                      A set of sortable columns
         */
        private function getSortableColumns(event:*):Boolean
        {
            var rtv:Boolean=false;

            if (!event.isError)
            {
                sortableColumns=new ArrayCollection();
                for each (var record:* in event.data.child("Record"))
                {
                    sortableColumns.addItem(record['Column_name'].toString());
                }
                rtv=true;
            }

            return rtv;
        }

        /**
         * Gets the total number of pages of the list view from a server response.
         * @param event                 A server response
         * @return                      true-Updated, false-Not updated
         */
        private function getPageNumbers(event:*):Boolean
        {
            return true;
        }

        /**
         * Gets a set of columns from a XML object.
         * @param resultSet             A XML object
         * @return                      A set of columns
         */
        private function getColumns(resultSet:XML):ArrayCollection
        {
            var rtv:ArrayCollection=new ArrayCollection();
            var dgc:DataGridColumn;
            var columnInfo:String;
            var maxStringLength:Number=0;

            var xmlDoc:XMLDocument=new XMLDocument();
            xmlDoc.parseXML(resultSet.child("Record").toXMLString());

            var columnData:Array=new Array();

            var searchComboData:ArrayCollection=new ArrayCollection();
            searchComboData.addItem({label: 'All Fields', columnName: 'all', alias: '', type: 'string'});

            if (xmlDoc.firstChild != null)
            {
                for each (var colNode:XMLNode in xmlDoc.firstChild.childNodes)
                {
                    if (colNode.nodeName != null)
                    {
                        // Instantiates a DataGridColumn.
                        dgc=new DataGridColumn(colNode.nodeName);

                        // Sets the hearder text of this column.
                        dgc.headerText=getHeaderText(colNode.nodeName);

                        // Sets the backgroud color of this column.
//                        if ( WebClient_Workspace.HIGHLIGHTED_COLUMNS[listViewCallerID][dgc.dataField] != null ) {
//                            dgc.setStyle("backgroundColor", 0XE1E1E1);
//                        }
//                        else {
//                            dgc.setStyle("backgroundColor", 0XFFFFFF);
//                        }

                        // Gets the maximum width of the search combobox.
                        maxStringLength=Math.max(maxStringLength, dgc.headerText.length);

                        // Sets the properties of this column.
                        dgc.dataTipField=getColumnTypeFor(colNode.nodeName) + "," + getColumnAliasFor(colNode.nodeName);

                        // Sets the visibility of this column.
                        if (!isColumnRequired(colNode.nodeName))
                        {
                            dgc.visible=false;
                        }

                        // Sets the sortability of this column.
                        if (!isColumnSortable(colNode.nodeName))
                        {
                            dgc.sortable=false;
                        }

                        // Sets the order status of this column.
                        if (orderColumnData['name'] == colNode.nodeName)
                        {
                            if (orderColumnData['order'] == 'DESC')
                            { // Descending order
                                dgc.sortDescending=true;
                            }
                            else
                            { // Ascending order
                                dgc.sortDescending=false;
                            }
                        }

//                        // Sets the size of this column.
//                        if ( WebClient_Workspace.COLUMN_SIZES[listViewCallerID][colNode.nodeName] > 0 ) {
//                            dgc.width = WebClient_Workspace.COLUMN_SIZES[listViewCallerID][colNode.nodeName];
//                        }
//                        
//                        // Sets the item renderer of this column.
//                        if ( WebClient_Workspace.COLUMN_RENDERERS[listViewCallerID][colNode.nodeName] != null ) {
//                            dgc.itemRenderer = WebClient_Workspace.COLUMN_RENDERERS[listViewCallerID][colNode.nodeName];
//                        }
//                        
//                        if ( (WebClient_Workspace.COLUMN_TYPES[listViewCallerID][colNode.nodeName] == "currency") || 
//                             (WebClient_Workspace.COLUMN_TYPES[listViewCallerID][colNode.nodeName] == "number") ) 
//                        {
//                            // Sets the label function of this column.
//                            if ( WebClient_Workspace.COLUMN_LABEL_FUNCTIONS[listViewCallerID][colNode.nodeName] != null ) {
//                                dgc.setStyle("textAlign", "right");
//                                dgc.labelFunction = 
//                                   WebClient_Workspace.COLUMN_LABEL_FUNCTIONS[listViewCallerID][colNode.nodeName];
//                            }
//                            
//                            // Sets the sort function of this column.
//	                        if ( WebClient_Workspace.COLUMN_SORT_FUNCTIONS[listViewCallerID][colNode.nodeName] != null ) {
//	                            dgc.sortCompareFunction = 
//	                               WebClient_Workspace.COLUMN_SORT_FUNCTIONS[listViewCallerID][colNode.nodeName];
//	                        }
//                        }

                        // Adds a list item to the search combobox.
                        if (isColumnRequired(colNode.nodeName))
                        {
                            searchComboData.addItem({label: getHeaderText(colNode.nodeName), columnName: colNode.nodeName, type: getColumnTypeFor(colNode.nodeName)});
                        }

                        // Adds this column to the list view.
                        columnData.push(dgc);

                        // Adds this column to the return data.
                        rtv.addItem(colNode.nodeName);
                    }
                }
            }
            // Else, in case of PHP, the returned result set is empty if there's no records..
            // Construct header information and such.
            else if (Constant.IS_PHP_SERVER)
            {
//                var columns:ArrayCollection = new ArrayCollection();
//                var keys:Object = ObjectUtil.getClassInfo(WebClient_Workspace.PHP_COLUMNS[listViewCallerID]);
//                
//                for each (var key:QName in keys.properties) {
//                    columns.addItem(
//                        {order:WebClient_Workspace.PHP_COLUMNS[listViewCallerID][key.localName], name:key.localName}
//                    );
//                }

//                if ( columns.length > 0 ) {
//                    var sort:Sort = new Sort();
//                    var sortField:SortField = new SortField("order");
//                    sortField.numeric = true;
//                    sort.fields = [sortField];
//                    columns.sort = sort;
//                    columns.refresh();
//                }

//                for each (var column:Object in columns) {
//                    //trace column.name;
//                    //var temp:String = column.name;
//                    if (column.name != null)
//                    {
//                        // Instantiates a DataGridColumn.
//                        dgc = new DataGridColumn(column.name);
//                        
//                        // Sets the hearder text of this column.
//                        dgc.headerText = getHeaderText(column.name);
//                        
//                        maxStringLength = Math.max(maxStringLength, dgc.headerText.length);
//                        
//                        // Sets the properties of this column.
//                        dgc.dataTipField = 
//                            getColumnTypeFor(column.name) + 
//                            "," + 
//                            getColumnAliasFor(column.name);
//                        
//                        // Sets the visibility of this column.
//                        if ( !isColumnRequired(column.name) ) {
//                            dgc.visible = false;
//                        }
//                        
//                        // Sets the sortability of this column.
//                        if ( !isColumnSortable(column.name) ) {
//                            dgc.sortable = false;
//                        }
//                        
//                        // Sets the order status of this column.
//                        if ( orderColumnData['name'] == column.name ) {
//                            if ( orderColumnData['order'] == 'DESC' ) {    // Descending order
//                                dgc.sortDescending = true;
//                            }
//                            else {                                         // Ascending order
//                                dgc.sortDescending = false;
//                            }
//                        }
//                        
//                        // Sets the size of this column.
//                        if ( WebClient_Workspace.COLUMN_SIZES[listViewCallerID][column.name] > 0 ) {
//                            dgc.width = WebClient_Workspace.COLUMN_SIZES[listViewCallerID][column.name];
//                        }
//                        
//                        // Sets the item renderer of this column.
//                        if ( WebClient_Workspace.COLUMN_RENDERERS[listViewCallerID][column.name] != null ) {
//                            dgc.itemRenderer = WebClient_Workspace.COLUMN_RENDERERS[listViewCallerID][column.name];
//                        }
//                        
//                        if ( (WebClient_Workspace.COLUMN_TYPES[listViewCallerID][column.name] == "currency") || 
//                             (WebClient_Workspace.COLUMN_TYPES[listViewCallerID][column.name] == "number") ) 
//                        {
//                            // Sets the label function of this column.
//                            if ( WebClient_Workspace.COLUMN_LABEL_FUNCTIONS[listViewCallerID][column.name] != null ) {
//                                dgc.setStyle("textAlign", "right");
//                                dgc.labelFunction = 
//                                   WebClient_Workspace.COLUMN_LABEL_FUNCTIONS[listViewCallerID][column.name];
//                            }
//                            
//                            // Sets the sort function of this column.
//                            if ( WebClient_Workspace.COLUMN_SORT_FUNCTIONS[listViewCallerID][column.name] != null ) {
//                                dgc.sortCompareFunction = 
//                                   WebClient_Workspace.COLUMN_SORT_FUNCTIONS[listViewCallerID][column.name];
//                            }
//                        }
//                        // Adds a list item to the search combobox.
//                        if ( isColumnRequired(column.name) ) {
//                            searchComboData.addItem({
//                                label:getHeaderText(column.name), 
//                                columnName:column.name, 
//                                type:getColumnTypeFor(column.name)
//                            });
//                        }
//                        
//                        // Adds this column to the list view.
//                        columnData.push(dgc);
//                        
//                        // Adds this column to the return data.
//                        rtv.addItem(column.name);
//                    }
//                }                
            }
            // Updates the search combobox on the list view.
            if (pageControlID == Constant.PAGE_CONTROL_ID_DEFAULT)
            {
                listView.ListView_SearchComboData=searchComboData;
            }

            // Updates the columns on the list view.
            listView.ListView_DataGrid.columns=columnData;

            // Sets the width of the search combobox.
            listView.ListView_SearchCombo.dropdownWidth=Math.max((maxStringLength * 7) + 10, listView.ListView_SearchCombo.width);

            // Sets a custom tooltip function.
//            if ( WebClient_Workspace.COLUMN_TOOLTIPS[listViewCallerID] != null ) {
//                toolTipProvider = WebClient_Workspace.COLUMN_TOOLTIPS[listViewCallerID];
//                listView.ListView_DataGrid.toolTip = " ";
//                listView.ListView_DataGrid.addEventListener(
//                    ToolTipEvent.TOOL_TIP_CREATE, 
//                    toolTipProvider.toolTipFunc);
//                listView.ListView_DataGrid.addEventListener(
//                    ListEvent.ITEM_ROLL_OVER, 
//                    toolTipProvider.itemRollOverFun);
//                listView.ListView_DataGrid.addEventListener(
//                    ListEvent.ITEM_ROLL_OUT, 
//                    toolTipProvider.itemRollOutFunc);
//            }
//            else {
//                if ( toolTipProvider != null ) {
//                    listView.ListView_DataGrid.toolTip = "";
//                    listView.ListView_DataGrid.removeEventListener(
//                        ToolTipEvent.TOOL_TIP_CREATE, 
//                        toolTipProvider.toolTipFunc);
//                    listView.ListView_DataGrid.removeEventListener(
//                        ListEvent.ITEM_ROLL_OVER, 
//                        toolTipProvider.itemRollOverFun);
//                    listView.ListView_DataGrid.removeEventListener(
//                        ListEvent.ITEM_ROLL_OUT, 
//                        toolTipProvider.itemRollOutFunc);
//                    toolTipProvider = null;
//                }
//            }
//            
            return rtv;
        }


        //########################################################################################
        /*
         * Helpers
         */
        /**
           /**
         * Encodes all special characters in a SQL statement.
         * @param str                   A SQL statement
         * @param                       An encoded SQL statement
         */
        private function dbEncode(str:String):String
        {
            var rtv:String=str;
            rtv=rtv.replace(/(\")/g, "%5C%22");
            rtv=rtv.replace(/[\\]/g, "\\\\");
            rtv=rtv.replace(/[']/g, "\\'");
            rtv=rtv.replace(/[=]/g, "\\=");
            rtv=rtv.replace(/(%5C%22)/g, "\\\"");
            return rtv;
        }

        /**
         * Displays an alert.
         * @param strTemp               A SQL statement
         */
        private var alertTitle:String;
        private var alertMessage:String;
        private var alertIcon:Class;

        private function alert(delay:Number, title:String, msg:String, icon:Class):void
        {
            alertTitle=title;
            alertMessage=msg;
            alertIcon=icon;
            var timer:Timer=new Timer(delay, 1);
            timer.addEventListener(TimerEvent.TIMER_COMPLETE, alertEventHandler);
            timer.start();
        }

        /**
         * An event handler to display an alert.
         * @param event                 Event
         */
        private function alertEventHandler(event:Event):void
        {
            if (event != null)
            {
                Alert.show(alertMessage, alertTitle, Alert.OK, null, null, alertIcon, Alert.OK);
            }
        }

        /**
         * Returns the header text of a column.
         * @columnName                  A column field
         * @return                      A header text
         */
        private function getHeaderText(columnName:String):String
        {
            var rtv:String=columnName;
//            var func:Function = WebClient_Workspace.COLUMN_HEADER_TEXT_OVERRIE_FUNCTIONS[listViewCallerID][columnName];
//            
//            if ( func != null ) {
//                rtv = func({"callerID":listViewCallerID, "column":columnName, "year":yearFilter, "month":monthFilter});
//            }
//            else {
//                rtv = WebClient_Workspace.COLUMN_HEADERS[listViewCallerID][columnName];
//            }

            return rtv;
        }

        /**
         * Returns the visibility of a column.
         * @param columnName            A column name
         * @return                      true-Visible, false-Invisible
         */
        public function isColumnRequired(columnName:String):Boolean
        {
            var rtv:Boolean=true;
//            var func:Function = WebClient_Workspace.COLUMN_VISIBILITY_OVERRIDE_FUNCTIONS[listViewCallerID][columnName];
//            
//            if ( func != null ) {
//                rtv = func({"callerID":listViewCallerID, "column":columnName, "year":yearFilter, "month":monthFilter});
//            }
//            else {
//                if ( WebClient_Workspace.COLUMN_VISIBILITIES[listViewCallerID][columnName] == '0' ) {
//                    rtv = false;
//                }
//            }

            return rtv;
        }

        /**
         * Returns the sortability of a column.
         * @param columnName            A column name
         * @return                      true-Sortable, false-Not sortable
         */
        private function isColumnSortable(columnName:String):Boolean
        {
            var rtv:Boolean=false;
//            
//            if ( (columnName != null) && (columnName != '') ) {
//                // Dynamic Control
//                if ( sortableColumns != null ) {
//                    for each ( var column:String in sortableColumns ) {
//                        if ( column == columnName ) {
//                            rtv = true;
//                        }
//                    }
//                }
//                
//                // Static Control
//                if ( WebClient_Workspace.COLUMN_SORTABILITIES[listViewCallerID][columnName] == '1' ) {
//                    rtv = true;
//                }
//            }

            return rtv;
        }

        /**
         * Returns the type of a column.
         * @param columnName            A column name
         * @return                      A column type
         */
        private function getColumnTypeFor(columnName:String):String
        {
            var rtv:String='';
//            rtv = WebClient_Workspace.COLUMN_TYPES[listViewCallerID][columnName];
            return rtv;
        }

        /**
         * Returns the alias of a column.
         * @param columnName            A column name
         * @return                      A column alias
         */
        private function getColumnAliasFor(columnName:String):String
        {
            var rtv:String='';
//            rtv = WebClient_Workspace.COLUMN_ALIAS[listViewCallerID][columnName];
            return rtv;
        }


    }

}


